package com.brossdong.socket.netty.runtime;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;

/**
 * Created by brossdong on 2018/2/24.
 */
public class Server {

    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();

        ServerBootstrap b = new ServerBootstrap();

        b.group(bossGroup,workGroup)
         .channel(NioServerSocketChannel.class)
         .option(ChannelOption.SO_BACKLOG,1024)
         //设置日志
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new ChannelInitializer<SocketChannel>() {
             @Override
             protected void initChannel(SocketChannel sc) throws Exception {
                 //jboss编解码
                 sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
                 sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());

                 //
                 sc.pipeline().addLast(new ReadTimeoutHandler(5));
                 //处理逻辑
                 sc.pipeline().addLast(new ServerHandler());
             }
         });

        //设置连接端口
        ChannelFuture cf = b.bind(8765).sync();

        //关闭
        cf.channel().closeFuture().sync();
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
    }



}
